package com.edp.buscabus;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.content.Context;

import com.edp.buscabus.db.Coord;
import com.edp.buscabus.db.CoordDao;
import com.edp.buscabus.db.Lines;
import com.edp.buscabus.db.LinesDao;
import com.edp.buscabus.db.LinesDao.Properties;
import com.googlecode.androidannotations.annotations.Background;
import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;

@EBean
public class KmlOperation {

   @RootContext Context activity;
   private final String TAGBUS = "Placemark";

   int n;
   private Document doc = null;
   
   public static void main(String[] var0) {
      KmlOperation var1 = new KmlOperation();
//      var1.getBusForCode(11).toString();
      var1.getAllLines();
   }

   public Document loadXMLFromString(String f) throws Exception {
      InputStream is = activity.getAssets().open(f);
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      return builder.parse(is);
   }
   
   public List<String> getAllLines() {
       List<String> lines = new ArrayList<String>();
       try {
    	   if(doc == null)
    		   doc = loadXMLFromString("doc.kml");
           NodeList nl = doc.getElementsByTagName(TAGBUS);
           for(int i=0;i<nl.getLength();i++){
               NodeList content = nl.item(i).getChildNodes();
               String line = content.item(1).getTextContent();
               lines.add(line);
           }
       } catch (Exception e) {
           e.printStackTrace();
           return null;
       }
       return lines;
   }

//   public LineInfo getBusForCode(int cod) {
//       LineInfo bi = null;
//       try {
//    	   if(doc == null)
//    		   doc = loadXMLFromString("doc.kml");
//           NodeList nl = doc.getElementsByTagName(TAGBUS);
//           for(int i=0;i<nl.getLength();i++){
//               NodeList content = nl.item(i).getChildNodes();
//               String[] name = content.item(1).getTextContent().split(" - ");
//               if(cod == Integer.parseInt(name[0])){
//                   bi = new LineInfo();
//                   bi.setCod(Integer.parseInt(name[0]));
//                   bi.setName(name[1]);
//                   bi.setDesc(content.item(3).getTextContent());
//                   String coor = content.item(7).getChildNodes().item(3).getTextContent().trim();
//                   ArrayList<LatLng> c = new ArrayList<LatLng>();
//                   String[] split = coor.split(",0 ");
//                   for (String string : split) {
//                	   String[] lnglat = string.split(",");
//                	   double lat = Double.parseDouble(lnglat[1]);
//                	   double lng = Double.parseDouble(lnglat[0]);
//                	   c.add(new LatLng(lat, lng));
//                   }
//                   bi.setCoords(c);
//                   break;
//               }               
//           }
//       } catch (Exception e) {
//           e.printStackTrace();
//       }
//       return bi;
//   }

   public void cadLines(MainActivity main, int t, LinesDao linesDao, CoordDao coordDao) {
       try {
    	   if(doc == null)
    		   doc = loadXMLFromString("doc.kml");
    	   n = 0;
           NodeList nl = doc.getElementsByTagName(TAGBUS);
           for(int i=0; i<nl.getLength(); i++){
               NodeList content = nl.item(i).getChildNodes(); 
               String[] data = content.item(1).getTextContent().split(" - ");
               int l_cod = Integer.parseInt(data[0]);
               String l_name = data[1]; 
               String l_sentido = data[2];
               String l_desc = content.item(3).getTextContent();
               String l_coord = content.item(7).getChildNodes().item(3).getTextContent().trim();
        	   main.setPdTitle("Cadastrando linhas..." + n + " de " + t);
    	       main.setPdMessage(l_name); 
			   List<Lines> list = linesDao.queryBuilder().where(Properties.Cod.eq(l_cod)).list();
               if(list.isEmpty()){
            	   if(l_sentido.equals("Ida"))
                       linesDao.insert(new Lines(null, l_cod, l_name, l_desc, l_coord, ""));
            	   else
                       linesDao.insert(new Lines(null, l_cod, l_name, l_desc, "", l_coord));
               }else{
            	   Lines line = list.get(0);
            	   if(l_sentido.equals("Ida"))
            		   line.setCoords(l_coord);
            	   else
            		   line.setCoordsV(l_coord);
            	   linesDao.update(line);
               }
               n++; 
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   @Background
   public void cadCoord(CoordDao coordDao, int l_cod, String l_name, 
		   String l_sentido, String l_coord) {
	   String[] split = l_coord.split(",0 ");
	   for (String string : split) {
		   String[] lnglat = string.split(",");
		   double lng = Double.parseDouble(lnglat[0]);
		   double lat = Double.parseDouble(lnglat[1]);     
			int sentido = (l_sentido.equals("Ida")) ? 0 : 1;
			coordDao.insert(new Coord(null, lat, lng, l_cod, sentido));
	   }
	}
	
}
